//
//  WelcomeViewController.swift
//  SinaWeibo
//
//  Created by mac on 16/2/20.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage
class WelcomeViewController: UIViewController {

    override func loadView() {
        view = UIImageView(image: UIImage(named: "ad_background"))
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        //执行动画效果
        startAnimation()
    }
    private func setupUI(){
        view.addSubview(iconView)
        view.addSubview(welcomeLabel)
        
        //设置子视图的约束
        iconView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(view.snp_centerX)
            //自动布局的时候 一般需要写相对的约束
            make.bottom.equalTo(view.snp_bottom).offset(-160)
        }
        welcomeLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(iconView.snp_centerX)
            make.top.equalTo(iconView.snp_bottom).offset(16)
        }
        //最初文案是隐藏的 等到用户头像动画结束时  在显示欢迎文案
        welcomeLabel.alpha = 0
        
        
        //设置用户头像
        iconView.sd_setImageWithURL(AccountViewModel.sharedAccountViewModel.headImageURL)
        iconView.layer.cornerRadius = 45
        iconView.layer.masksToBounds = true
        
    }
    func startAnimation(){
        let offset = -UIScreen.mainScreen().bounds.height + 160
        
        self.iconView.snp_updateConstraints(closure: { (make) -> Void in
            make.bottom.equalTo(self.view.snp_bottom).offset(offset)
        })
        
        UIView.animateWithDuration(1.2, delay: 0, usingSpringWithDamping: 0.98, initialSpringVelocity: 9.8, options: [], animations: { () -> Void in
            //设置强制更新页面 提前更新页面  这一段代码必须写到动画闭包中
            self.view.layoutIfNeeded()
            }) { (_) -> Void in
                //显示欢迎文案
                UIView.animateWithDuration(0.5, animations: { () -> Void in
                    self.welcomeLabel.alpha = 1
                    }, completion: { (_) -> Void in
                        NSNotificationCenter.defaultCenter().postNotificationName(KChoseRootVC, object: "welcome")
                })
        }
    }

    //懒加载用户头像
    private lazy var iconView:UIImageView = UIImageView(image: UIImage(named: "avatar_default_big"))
//    private lazy var welcomeLabel:UILabel = UILabel(text: "欢迎您归来", fontSize: 16, textColor: UIColor.darkGrayColor())
    private lazy var welcomeLabel: UILabel = UILabel(text: (AccountViewModel.sharedAccountViewModel.userName ?? "") + "欢迎归来", fontSize: 19, textColor: UIColor.darkGrayColor())
    
}
